<template>
  <div class="emoji-panel">
    <!-- 表情包标签页 -->
    <view class="emoji-tabs">
      <view
        class="emoji-tab"
        :class="{ 'active-tab': activeTab === 'default' }"
        @click="switchToDefaultTab"
      >
        <text>默认表情</text>
      </view>
      <view
        class="emoji-tab"
        :class="{ 'active-tab': activeTab === 'custom' }"
        @click="switchToCustomTab"
      >
        <text>我的表情</text>
      </view>
    </view>

    <!-- 表情包内容区域 -->
    <swiper
      class="emoji-swiper"
      :current="activeTab === 'default' ? 0 : 1"
      @change="handleTabChange"
    >
      <!-- 默认表情 -->
      <swiper-item>
        <scroll-view
          scroll-y
          class="emoji-scroll"
          v-if="defaultEmoticons.length > 0"
        >
          <view class="emoji-list">
            <view
              class="emoji-item"
              v-for="(emoji, index) in defaultEmoticons"
              :key="'default-' + index"
              @click="selectEmoji(emoji)"
            >
              <text class="emoji-text" v-if="!isImageUrl(emoji)">{{
                emoji
              }}</text>
              <image
                v-else
                class="emoji-image"
                :src="emoji"
                mode="aspectFit"
              ></image>
            </view>
          </view>

          <!-- 空状态 -->
          <view
            class="emoji-empty"
            v-if="defaultEmoticons.length === 0 && !isLoadingEmoticons"
          >
            <text>暂无默认表情</text>
          </view>
        </scroll-view>
      </swiper-item>

      <!-- 用户表情包 -->
      <swiper-item>
        <scroll-view scroll-y class="emoji-scroll">
          <view class="emoji-list">
            <!-- 添加表情按钮放在开头 -->
            <view class="emoji-item add-emoji-item" @click="addEmoji">
              <view class="add-emoji-icon">
                <FeatherIcon name="plus-square" size="40" color="#666" />
              </view>
            </view>

            <view
              class="emoji-item"
              v-for="(emoji, index) in customEmoticons"
              :key="'custom-' + index"
              @click="selectEmoji(emoji)"
              @longpress="handleLongPress(index)"
            >
              <image
                class="emoji-image"
                :src="emoji"
                mode="aspectFit"
                :class="{
                  'emoji-delete-active': selectedEmojiIndex === index,
                }"
              ></image>
              <view
                class="emoji-delete-icon"
                v-if="selectedEmojiIndex === index"
                @click.stop="deleteEmoji(index)"
              >
                <FeatherIcon name="trash-2" size="24" color="#ff4d4f" />
              </view>
            </view>
          </view>

          <!-- 空状态 -->
          <view
            class="emoji-empty custom-empty"
            v-if="
              customEmoticons.length === 0 &&
              !isLoadingCustomEmoticons &&
              hasLoadedCustomEmoticons
            "
          >
            <text>暂无自定义表情</text>
          </view>
        </scroll-view>
      </swiper-item>
    </swiper>

    <!-- 加载中状态 -->
    <view
      class="emoji-loading"
      v-if="isLoadingEmoticons || isLoadingCustomEmoticons"
    >
      <text>加载表情中...</text>
    </view>
  </div>
</template>

<script setup>
import { ref, onMounted } from "vue";
import FeatherIcon from "@/components/FeatherIcon.vue";
import api from "@/api";
import {
  showLoading,
  hideLoading,
  showError,
  showSuccess,
} from "@/utils/common.js";
import { chooseAndUploadImage } from "@/utils/upload";

const emit = defineEmits(["select-emoji", "add-custom-emoji"]);

// 状态
const activeTab = ref("default");
const defaultEmoticons = ref([]);
const customEmoticons = ref([]);
const isLoadingEmoticons = ref(false);
const isLoadingCustomEmoticons = ref(false);
const hasLoadedCustomEmoticons = ref(false);
const selectedEmojiIndex = ref(-1);

// 切换到默认表情页
const switchToDefaultTab = () => {
  activeTab.value = "default";
  selectedEmojiIndex.value = -1; // 重置删除状态
  if (defaultEmoticons.value.length === 0 && !isLoadingEmoticons.value) {
    loadDefaultEmoticons();
  }
};

// 切换到自定义表情页
const switchToCustomTab = () => {
  activeTab.value = "custom";
  selectedEmojiIndex.value = -1; // 重置删除状态
  if (!hasLoadedCustomEmoticons.value && !isLoadingCustomEmoticons.value) {
    loadCustomEmoticons();
  }
};

// 处理标签页切换
const handleTabChange = (e) => {
  const current = e.detail.current;
  activeTab.value = current === 0 ? "default" : "custom";

  // 如果切换到自定义表情标签且未加载过
  if (
    current === 1 &&
    !hasLoadedCustomEmoticons.value &&
    !isLoadingCustomEmoticons.value
  ) {
    loadCustomEmoticons();
  }
};

// 加载默认表情
const loadDefaultEmoticons = async () => {
  if (isLoadingEmoticons.value) return;

  try {
    isLoadingEmoticons.value = true;
    // 加载默认表情
    const defaultRes = await api.chat.getDefaultEmoticon();
    if (defaultRes.code === 0) {
      // 处理特殊格式的默认表情包
      if (Array.isArray(defaultRes.data)) {
        // 检查是否是每个元素都是一个对象，且对象只有一个键值对的格式
        const firstItem = defaultRes.data[0];
        if (
          firstItem &&
          typeof firstItem === "object" &&
          Object.keys(firstItem).length === 1
        ) {
          // 特殊格式：[{smile: "😄"}, {flushed: "😳"}, ...]
          // 将其转换为表情符号数组
          defaultEmoticons.value = defaultRes.data.map((item) => {
            const key = Object.keys(item)[0];
            return item[key];
          });
        } else {
          // 普通数组格式，直接使用
          defaultEmoticons.value = defaultRes.data;
        }
      } else if (defaultRes.data && typeof defaultRes.data === "object") {
        // 如果是对象格式，尝试提取emotions字段或其他数组字段
        defaultEmoticons.value =
          defaultRes.data.emotions ||
          Object.values(defaultRes.data).find((val) => Array.isArray(val)) ||
          [];
      } else {
        defaultEmoticons.value = [];
      }
    }
  } catch (error) {
    console.error("加载默认表情包失败", error);
    defaultEmoticons.value = [];
  } finally {
    isLoadingEmoticons.value = false;
  }
};

// 加载自定义表情
const loadCustomEmoticons = async () => {
  if (isLoadingCustomEmoticons.value) return;

  try {
    isLoadingCustomEmoticons.value = true;
    // 加载用户表情包
    const customRes = await api.chat.getEmoticon();
    if (customRes.code === 0) {
      if (Array.isArray(customRes.data)) {
        // 检查是否是与默认表情包相同的特殊格式
        const firstItem = customRes.data[0];
        if (
          firstItem &&
          typeof firstItem === "object" &&
          Object.keys(firstItem).length === 1
        ) {
          // 特殊格式，将其转换为表情符号或URL数组
          customEmoticons.value = customRes.data
            .map((item) => {
              const key = Object.keys(item)[0];
              return item[key];
            })
            .reverse(); // 反转顺序，最新的在前面
        } else {
          // 普通数组格式
          customEmoticons.value = [...customRes.data].reverse(); // 反转顺序，最新的在前面
        }
      } else if (
        customRes.data &&
        typeof customRes.data === "string" &&
        customRes.data.trim()
      ) {
        try {
          const parsedData = JSON.parse(customRes.data);
          if (Array.isArray(parsedData)) {
            // 同样检查特殊格式
            const firstItem = parsedData[0];
            if (
              firstItem &&
              typeof firstItem === "object" &&
              Object.keys(firstItem).length === 1
            ) {
              customEmoticons.value = parsedData
                .map((item) => {
                  const key = Object.keys(item)[0];
                  return item[key];
                })
                .reverse(); // 反转顺序，最新的在前面
            } else {
              customEmoticons.value = [...parsedData]; // 已经是反转过的，保持原样
            }
          } else if (parsedData && typeof parsedData === "object") {
            // 尝试从对象中提取数组
            const possibleArray = Object.values(parsedData).find((val) =>
              Array.isArray(val)
            );
            if (possibleArray) {
              customEmoticons.value = [...possibleArray].reverse(); // 反转顺序，最新的在前面
            } else {
              console.log("表情包数据格式不是数组:", parsedData);
              customEmoticons.value = [];
            }
          } else {
            console.log("表情包数据格式不正确:", parsedData);
            customEmoticons.value = [];
          }
        } catch (e) {
          console.error("解析表情包数据失败", e);
          console.log("原始数据:", customRes.data);
          customEmoticons.value = [];
        }
      } else {
        console.log("表情包数据为空或非法格式");
        customEmoticons.value = [];
      }
    } else {
      console.log("获取表情包失败:", customRes.msg);
      customEmoticons.value = [];
    }
    hasLoadedCustomEmoticons.value = true;
  } catch (error) {
    console.error("加载自定义表情包失败", error);
    customEmoticons.value = [];
  } finally {
    isLoadingCustomEmoticons.value = false;
  }
};

// 添加自定义表情
const addEmoji = () => {
  chooseAndUploadImage({
    count: 1,
    loadingText: "上传中...",
    showSuccessTip: false,
  })
    .then(async (imageUrl) => {
      try {
        // 向自定义表情列表添加新表情 - 添加到数组前面，而不是末尾
        const newCustomEmoticons = [imageUrl, ...customEmoticons.value];
        // 同步到服务器
        await api.chat.syncEmoticon(
          "emojis",
          JSON.stringify(newCustomEmoticons)
        );
        // 更新本地表情列表
        customEmoticons.value = newCustomEmoticons;

        emit("add-custom-emoji", imageUrl);
        showSuccess("添加表情成功");
      } catch (error) {
        console.error("添加表情到服务器失败:", error);
        showError(error.message || "添加表情失败");
      }
    })
    .catch((error) => {
      console.error("选择或上传图片失败:", error);
    });
};

// 选择表情
const selectEmoji = (emoji) => {
  emit("select-emoji", emoji);
};

// 长按表情触发删除模式
const handleLongPress = (index) => {
  // 只允许删除自定义表情
  if (activeTab.value === "custom") {
    selectedEmojiIndex.value = index;
  }
};

// 删除表情
const deleteEmoji = async (index) => {
  try {
    uni.showModal({
      title: "删除表情",
      content: "确定要删除这个表情吗？",
      success: async (res) => {
        if (res.confirm) {
          showLoading("删除中...");

          // 复制一份表情数组并移除选中项
          const newCustomEmoticons = [...customEmoticons.value];
          newCustomEmoticons.splice(index, 1);

          // 同步到服务器
          await api.chat.syncEmoticon(
            "emojis",
            JSON.stringify(newCustomEmoticons)
          );

          // 更新本地表情列表
          customEmoticons.value = newCustomEmoticons;

          // 重置选中状态
          selectedEmojiIndex.value = -1;

          showSuccess("删除成功");
        } else {
          // 取消删除
          selectedEmojiIndex.value = -1;
        }
      },
    });
  } catch (error) {
    console.error("删除表情失败:", error);
    showError(error.message || "删除失败");
    selectedEmojiIndex.value = -1;
  } finally {
    hideLoading();
  }
};

// 判断是否为图片URL
const isImageUrl = (emoji) => {
  if (!emoji || typeof emoji !== "string") return false;
  return (
    emoji.startsWith("http") &&
    (emoji.endsWith(".png") ||
      emoji.endsWith(".jpg") ||
      emoji.endsWith(".jpeg") ||
      emoji.endsWith(".gif") ||
      emoji.endsWith(".webp") ||
      emoji.includes(".png?") ||
      emoji.includes(".jpg?") ||
      emoji.includes(".jpeg?") ||
      emoji.includes(".gif?") ||
      emoji.includes(".webp?"))
  );
};

// 组件挂载时加载默认表情
onMounted(() => {
  loadDefaultEmoticons();
});
</script>

<style lang="scss" scoped>
.emoji-panel {
  width: 100%;
  height: 420rpx;
  background-color: #fff;
  border-top: 1px solid rgba(0, 0, 0, 0.05);
  box-sizing: border-box;
  overflow: hidden;
  transition: all 0.3s;
  margin-top: 20rpx;
  display: flex;
  flex-direction: column;
  position: relative;
}

.emoji-tabs {
  display: flex;
  justify-content: space-around;
  padding: 10rpx 0;
}

.emoji-tab {
  padding: 10rpx 30rpx;
  font-size: 28rpx;
  color: #666;
  position: relative;
  transition: all 0.3s;
}

.active-tab {
  color: #0072ff;
  font-weight: 500;
}

.active-tab::after {
  content: "";
  position: absolute;
  bottom: 0;
  left: 50%;
  transform: translateX(-50%);
  width: 60rpx;
  height: 4rpx;
  background-color: #0072ff;
  border-radius: 4rpx;
}

.emoji-swiper {
  flex: 1;
  height: 200rpx;
}

.emoji-scroll {
  height: 100%;
  padding: 10rpx;
}

.emoji-list {
  display: flex;
  flex-wrap: wrap;
  padding: 10rpx;
}

.emoji-item {
  width: 100rpx;
  height: 100rpx;
  margin: 10rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  position: relative;
}

.emoji-image {
  width: 80rpx;
  height: 80rpx;
  object-fit: contain;
}

.emoji-text {
  font-size: 40rpx;
  line-height: 80rpx;
  text-align: center;
}

.emoji-loading {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  background-color: rgba(255, 255, 255, 0.8);
  color: #999;
  font-size: 28rpx;
}

.emoji-empty {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 60rpx 0;
  color: #999;
  font-size: 28rpx;
  height: 100%;
}

.custom-empty {
  padding-top: 100rpx;
}

.add-emoji-btn {
  margin-top: 30rpx;
  background-color: #0072ff;
  color: #fff;
  font-size: 26rpx;
  padding: 12rpx 30rpx;
  border-radius: 30rpx;
}

.add-emoji-item {
  display: flex;
  justify-content: center;
  align-items: center;
}

.add-emoji-icon {
  display: flex;
  justify-content: center;
  align-items: center;
}

.emoji-delete-active {
  opacity: 0.5;
}

.emoji-delete-icon {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  background-color: rgba(255, 255, 255, 0.8);
  border-radius: 50%;
  width: 60rpx;
  height: 60rpx;
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 10rpx;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.2);
  z-index: 10;
}
</style>
